<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="936"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[460px]">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
      >
        <template #far_fee-slot>
          <div
            class="text-[13px] text-[#9DA1AD] mt-[5px] w-[100%] leading-[24px]"
          >
            偏远费用系统逻辑为，检测到订单地址上，此国家（目地的），地址详情上有设置的地区名称(省市区地址详情1，地址详情2)或订单邮编吻合，则满足偏远费用，会把设置的偏远费用加到运费里面去
          </div>
        </template>
        <template #farFeePre> ￥ </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import { overallOptions } from '@/api/public'

import { createFarAddress, updateFarAddress, farAddressDetail } from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  labelPosition: 'top',
}

const rules = {
  channel_id: [
    { required: true, message: '请选择中文渠道名称', trigger: 'blur' },
  ],
  address_name:[
    { required: true, message: '请输入偏远地址名称', trigger: 'blur' },
  ]
}

const form = ref()
const model = ref({})
const loading = ref()
const orderData = ref()

const fieldList = [
  {
    field: 'channel_id',
    label: '中文渠道名称',
    origin: 'map.channel',
    type: 'select',
    multiple: true,
    options: {
      labelKey: 'channel_name',
      valueKey: 'channel_id',
    },
  },
  { field: 'address_name', label: '偏远地址名称' },
  {
    field: 'country',
    label: '国家',
    origin: 'map.country',
    multiple: true,
    options: {
      valueKey: 'country',
      labelKey: 'country_name',
    },
    type: 'select',
  },
  {
    field: 'area',
    label: '地区',
    type: 'textarea',
    autosize: { minRows: 2, maxRows: 6 },
    placeholder: '一行一个或者 ; 号隔开',
  },
  {
    field: 'zip_code',
    label: '邮编',
    autosize: { minRows: 2, maxRows: 6 },
    type: 'textarea',
    placeholder: '一行一个或者 ; 号隔开',
  },
  {
    field: 'far_fee',
    label: '偏远费用',
    type: 'Number',
    prefix: 'farFeePre',
    min: 0,
  },
]

watch(
  () => props.id,
  val => {
    if (val) {
      nextTick(() => {
        getDetail(val)
      })
    }
  }
)
const getDetail = async id => {
  try {
    const { data } = await farAddressDetail({ id })

    model.value = {
      ...data,
    }
  } catch (e) {
    orderData.value = {}
    console.error(e)
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const formInfo = await form.value.submit()
    console.warn(formInfo)
    const api = {
      edit: updateFarAddress,
      add: createFarAddress,
    }
    const { id } = props

    const { logistics_api, channel, shipping } = formInfo
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
